package com.suke.czx.modules.supplier.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;
import com.suke.czx.common.utils.*;
import com.suke.czx.common.validate.SupplierSaveGroup;
import com.suke.czx.common.validate.SupplierUpdateGroup;
import com.suke.czx.modules.product.service.ProductService;
import com.suke.czx.modules.supplier.entity.Supplier;
import com.suke.czx.modules.supplier.service.SupplierService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 应用模块名称: 供应商
 * 代码描述: 供应商控制层
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2021/08/31 15:30:50
 */
@Validated
@RestController
@RequestMapping("/api/supplier")
@AllArgsConstructor
@Api(value = "SupplierController", tags = "供应商管理")
public class SupplierController extends AbstractController {

    private final SupplierService supplierService;

    private final ProductService productService;

    /**
     * 分页查询供应商列表
     * @param params 查询参数
     * @return VO
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:supplier:list')")
    public R list(@RequestParam Map<String, Object> params) {
        if (StrUtil.isBlankIfStr(params.get(FieldConstant.PAGE)) || StrUtil.isBlankIfStr(FieldConstant.LIMIT)) {
            return R.error("缺少分页信息");
        }
        // 查询列表数据
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.DEL_FLG, CodeConstant.NOT_DEL);
        if (params.size() > 2){
            queryWrapper.like(!StrUtil.isBlankIfStr(params.get(FieldConstant.COMPANY_NAME)), StrUtil.toUnderlineCase(FieldConstant.COMPANY_NAME), params.get(FieldConstant.COMPANY_NAME))
                    .like(!StrUtil.isBlankIfStr(params.get(FieldConstant.BUSINESS_SCOPE)), StrUtil.toUnderlineCase(FieldConstant.BUSINESS_SCOPE), params.get(FieldConstant.BUSINESS_SCOPE))
                    .like(!StrUtil.isBlankIfStr(params.get(FieldConstant.PRODUCT_IDS)), StrUtil.toUnderlineCase(FieldConstant.PRODUCT_IDS), params.get(FieldConstant.PRODUCT_IDS));
        }
        IPage<Supplier> customerPage = supplierService.page(mpPageConvert.pageParamConvert(params), queryWrapper);
        // 设置产品名称
        customerPage.getRecords().forEach(s -> s.setProductNames(productService.selectProduct(s.getProductIds()).stream().map(i -> i.getBrand() + "-" + i.getProductName()).collect(Collectors.joining(Constant.COMMA))));
        return Objects.requireNonNull(R.ok().put(FieldConstant.TOTAL, customerPage.getTotal())).setData(Optional.ofNullable(customerPage.getRecords()).orElse(Lists.newArrayList()));
    }

    /**
     * 查询所有供应商
     * @return VO
     */
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:supplier:select')")
    public R select() {
        // 查询所有数据
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.DEL_FLG, CodeConstant.NOT_DEL);
        return R.ok().setData(Optional.ofNullable(supplierService.list(queryWrapper)).orElse(Lists.newArrayList()));
    }

    /**
     * 获供应商详情
     * @param supplierId 供应商id
     * @return VO
     */
    @RequestMapping(value = "/info/{supplierId}", method = RequestMethod.GET)
    @PreAuthorize("hasRole('but:supplier:info')")
    public R info(@PathVariable("supplierId") Long supplierId) {
        Supplier supplier = supplierService.getById(supplierId);
        return R.ok().setData(supplier);
    }

    /**
     * 保存供应商
     * @param supplier 供应商
     * @param bindingResult bindingResult
     * @return VO
     */
    @SysLog("保存供应商")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:supplier:save')")
    public R save(@Validated(SupplierSaveGroup.class) Supplier supplier, BindingResult bindingResult) {
        // 入参校验结果
        if (bindingResult.hasErrors()) {
            return R.error(ParamValidateUtil.paramVilated(bindingResult));
        }
        // 校验供应商名称是否存在
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StrUtil.toUnderlineCase(FieldConstant.COMPANY_NAME), supplier.getCompanyName());
        if (ListUtil.size(supplierService.list(queryWrapper)) != 0) {
            return R.error("供应商名称已存在");
        }
        supplier.setCreator(getUserId());
        supplier.setCreateTime(new Date());
        supplierService.save(supplier);
        return R.ok();
    }

    /**
     * 更新供应商
     * @param supplier 供应商
     * @param bindingResult bindingResult
     * @return VO
     */
    @SysLog("更新供应商")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:supplier:update')")
    public R update(@Validated(SupplierUpdateGroup.class) Supplier supplier, BindingResult bindingResult) {
        // 入参校验结果
        if (bindingResult.hasErrors()) {
            return R.error(ParamValidateUtil.paramVilated(bindingResult));
        }
        supplier.setUpdater(getUserId());
        supplier.setUpdateTime(new Date());
        supplierService.updateById(supplier);
        return R.ok();
    }

    /**
     * 删除供应商
     * @param supplierId 供应商编码
     * @return VO
     */
    @SysLog("删除供应商")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:supplier:delete')")
    public R delete(@NotNull(message = "供应商编码不能为空") Long supplierId) {
        return supplierService.updateDelSupplier(supplierId, getUserId());
    }

}
